package deibay.server.backend.data;

import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.datamodel.Item;
import deibay.server.backend.ServerManager;
import deibay.server.eventargs.NotifyDeadlineItemEventArg;
import deibay.server.eventargs.RemoveItemEventArg;
import deibay.server.events.NotifyDeadlineItemEvent;
import deibay.server.events.RemoveItemEvent;
import deibay.util.IClosable;


public class Timer implements Runnable, IClosable{

	private Vector<Item> products = null;
	private boolean keepAlive;

	public Timer(Vector<Item> products)
	{
		this.products = products;
		keepAlive = true;
	}

	public void run() 
	{
		synchronized(products)		
		{
			while (products.isEmpty())
			{				
				try {
					products.wait();
				}catch (InterruptedException e1) {
					DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Excepao ao lancar um wait na thread Timer.\n");
				}			
			}
		}

		while(keepAlive == true)
		{		
			//System.err.println("OLAAA timer");
			
			Vector<Item> toRemove = new Vector<Item>();
			
			synchronized (products) {

				for(Item p: (Vector<Item>) products.clone())
				{
					Date now = new Date(System.currentTimeMillis());						
					if(now.getTime() > p.getFinishTime().getTime())
					{
						DeibayLogger.getInstance().getLog().log(Level.WARNING, "Leilao '"+p.toString()+"' chegou ao fim.\n");		
						toRemove.add(p);					
					}
				}
			}
			
			for (Item p : toRemove) {
				ServerManager.getInstance().getEventManager().fireEvent(new RemoveItemEvent(new RemoveItemEventArg(p)));
				ServerManager.getInstance().getEventManager().fireEvent(new NotifyDeadlineItemEvent(new NotifyDeadlineItemEventArg(p.toString(), p.getBidder(), p.getSeller(), p.getSubscribedUsers(), p.getActualPrice())));
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}	
		}
	}

	public void close() {
		keepAlive = false;		
	}
	
	public void restart()
	{
		keepAlive = true;
		new Thread(this).start();
	}
}

